package com.hc.springbootes;

import com.google.gson.Gson;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

//自定义结果映射
public class EmpResultMapper implements SearchResultMapper {

    @Override
    public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
        SearchHit[] searchHits = searchResponse.getHits().getHits();
        List<T> list = new ArrayList<>();
        for(SearchHit searchHit:searchHits){
            Map<String, Object> map = searchHit.getSourceAsMap();
            Map<String, HighlightField> highlightMap = searchHit.getHighlightFields();
            for(Map.Entry<String,HighlightField> highlightField: highlightMap.entrySet()){
                String key = highlightField.getKey();
                HighlightField value = highlightField.getValue();
                Text[] texts = value.getFragments();
                map.put(key,texts[0].toString());
            }
            Gson gson = new Gson();
            T t = gson.fromJson(gson.toJson(map), aClass);
            list.add(t);
        }
        return new AggregatedPageImpl<>(list,pageable,searchResponse.getHits().getTotalHits());
    }
}
